﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class StandaloneSignatureRule : ILRule<StandaloneSignatureHandle>
    {
        public byte[] Signature { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        [ILInfo]
        public StandaloneSignatureKind Kind { get; }

        public StandaloneSignatureRule(
            byte[] signature)
            : base()
        {
            Signature = signature;
        }

        public StandaloneSignatureRule(MetadataReader reader, StandaloneSignatureHandle standaloneSignatureHandle)
            : base(reader)
        {
            StandaloneSignature standaloneSignature = reader.GetStandaloneSignature(standaloneSignatureHandle);
            Signature = reader.GetBlobBytes(standaloneSignature.Signature);
            CustomAttributes = standaloneSignature.GetCustomAttributes();
            Kind = standaloneSignature.GetKind();
        }

        public override StandaloneSignatureHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddStandaloneSignature(
                signature: Signature == null ? default : builder.GetOrAddBlob(Signature));
        }
    }
}